#include <iostream>
#include <string>
#include<functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>
#include<cstdlib>
#include <cstring>
#include "Log.hpp"
#include"InetAddr.hpp"
enum error
{
    SOCKET_ERR = 1,
    BIND_ERR,
    USAGE_ERR,

};
using func_t=std::function<const std::string(const std::string&)>;
class UdpServer
{
public:
    UdpServer(uint16_t port,func_t func) : _port(port), _socketfd(-1),_func(func)
    {
    }
    void InitServer()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(FATAL, "socket error,%d,%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        LOG(INFO, "create socket success,socket:%d", _socketfd);

        struct sockaddr_in local;
        bzero(&local, sizeof(local)); 
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr=INADDR_ANY;

        int n = bind(_socketfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error,%d,%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        LOG(INFO, "bind success");
    }
    void start()
    {
        while (true)
        {
            char request[1024];
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            ssize_t n=recvfrom(_socketfd,request,sizeof(request)-1,0,(struct sockaddr*)&peer,&len);
            if(n>0)
            {
                request[n]=0;
                Addr addr(peer);
                LOG(DEBUG,"get request from[%s,%d]:%s",addr.IP().c_str(),addr.Port(),request);
                std::string respond=_func(request);
                sendto(_socketfd,respond.c_str(),respond.size(),0,(struct sockaddr*)&peer,len);
            }
        }
    }

private:
    int _socketfd;
    uint16_t _port;
    func_t _func;
};